import 'package:flutter/material.dart';
import 'package:flutter_09_game/base/widget/base_list_get_builder.dart';
import 'package:flutter_09_game/config/app_routes.dart';
import 'package:flutter_09_game/generated/assets.dart';
import 'package:flutter_09_game/generated/locales.g.dart';
import 'package:flutter_09_game/user/app_user_manager.dart';
import 'package:flutter_09_game/user/model/model_user_wallet.dart';
import 'package:flutter_09_game/utils/extensions/num_ext.dart';
import 'package:flutter_09_game/utils/log/utils_log.dart';
import 'package:flutter_09_game/utils/utils_image.dart';
import 'package:flutter_09_game/utils/utils_other.dart';
import 'package:flutter_09_game/widgets/appbar/common_app_bar.dart';
import 'package:flutter_09_game/widgets/crypto_tag_selector.dart';
import 'package:flutter_09_game/widgets/image/auto_image.dart';
import 'package:flutter_09_game/widgets/button/common_button.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:qr_flutter/qr_flutter.dart';
import '../../config/app_color.dart';
import 'deposit_logic.dart';

class DepositPage extends StatelessWidget {
  DepositPage({super.key});

  final DepositLogic logic = Get.put(DepositLogic());
  final GlobalKey _qrCodeKey = GlobalKey();

  @override
  Widget build(BuildContext context) {
    return BaseListGetBuilder<DepositLogic>(
      appBar: CommonAppBar(
        title: LocaleKeys.rechargeCenter.tr,
        showBack: false,
        actions: [
          GestureDetector(
            onTap: () {
              Get.toNamed(AppRoutes.depositRecordPage);
            },
            child: AutoImage(
              Assets.commonRecordBtn,
              width: 32.w,
            ),
          ),
          12.horizontalSpace,
          GestureDetector(
            onTap: () {
              AppUserManager().showServiceSheet();
            },
            child: AutoImage(
              Assets.commonServiceBtn,
              width: 32.w,
            ),
          ),
          10.horizontalSpace,
        ],
      ),
      builder: (_) {
        return Obx(() {
          if (AppUserManager().walletList.isEmpty) {
            // clog('1');
            return const SingleChildScrollView();
          } else {
            // clog('2');
            return SingleChildScrollView(
              padding: EdgeInsets.all(16.w),
              child: Column(
                children: [
                  // Container(
                  //   width: 100,
                  //   height: 100,
                  //   color: Colors.red,
                  // ),
                  // 顶部币种切换
                  CryptoTagSelector(
                    options: AppUserManager()
                        .walletList
                        .map((item) => item.symbol ?? '')
                        .toList(),
                    selectedValue: logic.userWallet.value.symbol ?? "",
                    onChanged: (symbol) {
                      ModelUserWallet? wallet = AppUserManager()
                          .walletList
                          .firstWhereOrNull((item) => item.symbol == symbol);
                      if (wallet != null) {
                        logic.userWallet.value = wallet;
                      }
                    },
                  ),

                  16.verticalSpaceFromWidth,

                  Container(
                    padding:
                        EdgeInsets.symmetric(horizontal: 12.w, vertical: 16.w),
                    decoration: BoxDecoration(
                        color: AppColor.navBgColor,
                        borderRadius: BorderRadius.circular(16.w)),
                    child: Column(
                      children: [
                        // 余额显示区域
                        _buildBalanceSection(),
                        // 24.verticalSpaceFromWidth,

                        // 充值地址和二维码区域
                        _buildDepositSection(),

                        // 温馨提示区域
                        _buildTipsSection(),
                        24.verticalSpaceFromWidth,

                        // 底部按钮区域
                        _buildBottomButtons(),
                      ],
                    ),
                  )
                ],
              ),
            );
          }
        });
      },
    );
    // return Scaffold(
    //   backgroundColor: AppColor.pageBgColor,
    //   body: SafeArea(
    //     child: Padding(
    //
    //   ),
    // );
  }

  /// 构建余额显示区域
  Widget _buildBalanceSection() {
    return Obx(() => Column(
          children: [
            // 余额标题
            Text(
              (logic.userWallet.value.symbol ?? '').toUpperCase() == 'USDT'
                  ? LocaleKeys.currentUsdtBalance.tr
                  : LocaleKeys.currentTrxBalance.tr,
              style: TextStyle(
                fontFamily: 'PingFang SC',
                fontSize: 14.sp,
                fontWeight: FontWeight.w500,
                color: AppColor.textPrimary.withOpacity(0.7),
              ),
            ),
            4.verticalSpaceFromWidth,

            // 余额金额和币种
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text(
                  logic.userWallet.value.balance.formatWallet(),
                  style: TextStyle(
                    fontSize: 20.sp,
                    fontWeight: FontWeight.w900,
                    color: AppColor.textPrimary.withOpacity(0.94),
                  ),
                ),
                8.horizontalSpace,
                Row(
                  children: [
                    AutoImage(
                      UtilsOther()
                          .getAmountTagIcon(logic.userWallet.value.symbol),
                      width: 20.w,
                      height: 20.w,
                    ),
                    4.horizontalSpace,
                    Text(
                      logic.userWallet.value.symbol ?? '',
                      style: TextStyle(
                        fontFamily: 'PingFang SC',
                        fontSize: 14.sp,
                        fontWeight: FontWeight.w400,
                        color: AppColor.textPrimary.withOpacity(0.7),
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ],
        ));
  }

  /// 构建充值区域
  Widget _buildDepositSection() {
    return Column(
      children: [
        // 充值说明

        RepaintBoundary(
            key: _qrCodeKey,
            child: Column(
              children: [
                Text(
                  LocaleKeys.usdtTrxDepositAddress.tr,
                  style: TextStyle(
                    fontFamily: 'PingFang SC',
                    fontSize: 12.sp,
                    fontWeight: FontWeight.w400,
                    color: AppColor.primary,
                    height: 1.0,
                  ),
                  textAlign: TextAlign.center,
                ),
                4.verticalSpaceFromWidth,
                Text(
                  LocaleKeys.autoDeposit.tr,
                  style: TextStyle(
                    fontFamily: 'PingFang SC',
                    fontSize: 12.sp,
                    fontWeight: FontWeight.w400,
                    color: AppColor.primary,
                    height: 1.0,
                  ),
                  textAlign: TextAlign.center,
                ),
                16.verticalSpaceFromWidth,
                ClipRRect(
                  borderRadius: BorderRadius.circular(12.w),
                  child: QrImageView(
                    data: AppUserManager().user.value?.rechargeAddress ?? '',
                    version: QrVersions.auto,
                    size: 154.w,
                    backgroundColor: Colors.white,
                  ),
                ),
                16.verticalSpaceFromWidth,
              ],
            )),

        // 地址复制区域
        Container(
          height: 52.w,
          padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 10.w),
          decoration: BoxDecoration(
            color: Colors.black.withOpacity(0.3), // rgba(0,0,0,0.3)
            borderRadius: BorderRadius.circular(8.w),
            border: Border(
                bottom: BorderSide(
              color: AppColor.textPrimary.withOpacity(0.15),
              width: 1.w,
            )),
          ),
          child: Row(
            children: [
              Expanded(
                child: Text(
                  logic.userWallet.value.user?.rechargeAddress ?? '',
                  // AppUserManager().user.value?.rechargeAddress ?? '',
                  style: TextStyle(
                    fontFamily: 'PingFang SC',
                    fontSize: 14.sp,
                    fontWeight: FontWeight.w400,
                    color: AppColor.textPrimary.withOpacity(0.94),
                  ),
                  overflow: TextOverflow.ellipsis,
                ),
              ),
              8.horizontalSpace,
              GestureDetector(
                  onTap: logic.copyAddress,
                  child: AutoImage(
                    Assets.gameCopy,
                    width: 32.w,
                  )),
            ],
          ),
        ),
      ],
    ).marginSymmetric(vertical: 24.w);
  }

  /// 构建温馨提示区域
  Widget _buildTipsSection() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          LocaleKeys.warmTips.tr,
          style: TextStyle(
            fontFamily: 'PingFang SC',
            fontSize: 12.sp,
            fontWeight: FontWeight.w600,
            color: AppColor.primary,
          ),
        ),
        8.verticalSpaceFromWidth,
        Obx(() {
          return _buildTipItem(
            '${LocaleKeys.registerTips1.tr}10 ${logic.userWallet.value.symbol?.toUpperCase()}；',
            highlightText:
                ' 10 ${logic.userWallet.value.symbol?.toUpperCase()}',
          );
        }),
        _buildTipItem(
          LocaleKeys.registerTips2.tr,
          highlightTexts: [
            LocaleKeys.highlightUnique.tr,
            LocaleKeys.highlightDedicatedAddress.tr,
            LocaleKeys.highlightPersonalOnly.tr,
            LocaleKeys.highlightDoNotShare.tr,
          ],
        ),
        _buildTipItem(
          LocaleKeys.registerTips3.tr,
          highlightTexts: [
            LocaleKeys.highlightThisPageDepositAddress.tr,
            LocaleKeys.highlightThisPageAddress.tr
          ],
        ),
        _buildTipItem(
          LocaleKeys.registerTips4.tr,
          highlightTexts: [
            LocaleKeys.highlightPageAddress2.tr,
            LocaleKeys.highlightCannotCredit.tr,
            LocaleKeys.highlightCannotRecover.tr
          ],
        ),
        _buildTipItem(
          LocaleKeys.registerTips5.tr,
          highlightText: LocaleKeys.highlightSmallTest.tr,
        ),
        _buildTipItem(
          LocaleKeys.registerTips6.tr,
          highlightText: LocaleKeys.highlightUsdtTrx.tr,
        ),
        _buildTipItem(
          LocaleKeys.registerTips7.tr,
        ),
      ],
    );
  }

  /// 构建提示项
  Widget _buildTipItem(String text,
      {String? highlightText, List<String>? highlightTexts}) {
    final highlights =
        highlightTexts ?? (highlightText != null ? [highlightText] : []);

    return Padding(
      padding: EdgeInsets.only(bottom: 4.w),
      child: RichText(
        text: TextSpan(
          style: TextStyle(
            fontFamily: 'PingFang SC',
            fontSize: 12.sp,
            fontWeight: FontWeight.w400,
            color: AppColor.textPrimary.withOpacity(0.5),
            height: 1.55,
          ),
          children: _buildHighlightedText(text, highlights),
        ),
      ),
    );
  }

  /// 构建高亮文本
  List<TextSpan> _buildHighlightedText(String text, List<String> highlights) {
    List<TextSpan> spans = [];
    String remainingText = text;

    for (String highlight in highlights) {
      final index = remainingText.indexOf(highlight);
      if (index != -1) {
        // 添加高亮前的文本
        if (index > 0) {
          spans.add(TextSpan(text: remainingText.substring(0, index)));
        }
        // 添加高亮文本
        spans.add(TextSpan(
          text: highlight,
          style: TextStyle(
            fontFamily: 'PingFang SC',
            fontSize: 12.sp,
            fontWeight: FontWeight.w600,
            color: AppColor.primary,
          ),
        ));
        // 更新剩余文本
        remainingText = remainingText.substring(index + highlight.length);
      }
    }

    // 添加剩余文本
    if (remainingText.isNotEmpty) {
      spans.add(TextSpan(text: remainingText));
    }

    return spans;
  }

  /// 构建底部按钮区域
  Widget _buildBottomButtons() {
    return Row(
      children: [
        Expanded(
          child: CommonButton(
            title: LocaleKeys.depositTutorial.tr,
            onClick: logic.openDepositTutorial,
            height: 44.w,
            fontSize: 14.sp,
            enable: false,
            alwaysCanClick: true,
          ),
        ),
        8.horizontalSpace,
        Expanded(
          child: CommonButton(
            title: LocaleKeys.saveQrCode.tr,
            onClick: () {
              UtilImage.saveImageToGallery(_qrCodeKey);
              // =>
              //     logic.saveQrCodeToGallery(_qrCodeKey)
            },
            height: 44.w,
            fontSize: 14.sp,
          ),
        ),
      ],
    );
  }
}
